package cn.chencq.moudle.sys.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.chencq.constants.Constants;
import cn.chencq.moudle.sys.entity.SysMenu;
import cn.chencq.moudle.sys.entity.SysUser;
import cn.chencq.moudle.sys.entity.SysUserToken;
import cn.chencq.moudle.sys.service.ShiroService;
import cn.chencq.moudle.sys.service.SysMenuService;
import cn.chencq.moudle.sys.service.SysUserService;
import cn.chencq.moudle.sys.service.SysUserTokenService;

@Service
public class ShiroServiceImpl implements ShiroService {

	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;

	@Override
	public Set<String> getUserPermissions(Long userId) {
		List<String> permsList;

		// 系统管理员，拥有最高权限
		if (userId == Constants.SUPER_ADMIN) {
			List<SysMenu> menuList = sysMenuService.queryList(null);
			permsList = new ArrayList<String>(menuList.size());
			for (SysMenu menu : menuList) {
				permsList.add(menu.getPerms());
			}
		} else {
			permsList = sysUserService.queryAllPermsByUserId(userId);
		}
		// 用户权限列表
		Set<String> permsSet = new HashSet<String>();
		for (String perms : permsList) {
			if (StringUtils.isBlank(perms)) {
				continue;
			}
			permsSet.addAll(Arrays.asList(perms.trim().split(",")));
		}
		return permsSet;
	}

	@Override
	public SysUserToken queryByToken(String accessToken) {
		return sysUserTokenService.queryByToken(accessToken);
	}

	@Override
	public SysUser queryUser(Long userId) {
		return sysUserService.selectByPrimaryKey(userId);
	}

}
